<?php

/**
 * Validates find form.
 *
 * @package    symfony
 * @subpackage validator
 * @author     Emeric Chevillard
 * @version    SVN: 
 */
class ValidatorPhasePlanning extends sfValidatorBase {
	public function __construct($field, $options = array(), $messages = array()) {
		$this->addOption('field', $field);
		parent::__construct($options, $messages);
	}
	
	/**
	 * @see sfValidatorBase
	 */
	public function configure($options = array(), $messages = array()) {
		$this->setMessage('invalid', 'Date invalide');
	}

	/**
	 * @see sfValidatorBase
	 */
	protected function doClean($values) {
		if ($values['plnphs_id']) {
			$taches = Doctrine::getTable('planning_tache')->findBy('plntac_plnphs_id', $values['plnphs_id'], Doctrine_Core::HYDRATE_RECORD);
			switch ($this->getOption('field')) {
				case 'plnphs_date_debut':
					$ok = true;
					$min_date = '2099-12-31';
					foreach ($taches as $tache) {
						$ok &= ($values['plnphs_date_debut'] <= $tache->getPlntacDateDebut());
						$min_date = min($min_date, $tache->getPlntacDateDebut());
					}
					if (!$ok) {
						$this->setMessage('invalid', 'La date de début doit être égale ou antérieure à celle des tâches ['.$min_date.']');
						throw new sfValidatorErrorSchema($this, array(
							'plnphs_date_debut' => new sfValidatorError($this, 'invalid')
						));
					}
					break;
				case 'plnphs_date_echeance':
					if ($values['plnphs_date_echeance'] != '') {
						$ok = true;
						$max_date = '2000-01-01';
						foreach ($taches as $tache) {
							$ok &= ($values['plnphs_date_echeance'] >= $tache->getPlntacDateEcheance());
							$max_date = max($max_date, $tache->getPlntacDateEcheance());
						}
						if (!$ok) {
							$this->setMessage('invalid', 'La date d\'échéance doit être égale ou postérieure à celle des tâches ['.$max_date.']');
							throw new sfValidatorErrorSchema($this, array(
								'plnphs_date_echeance' => new sfValidatorError($this, 'invalid')
							));
						}

						if ($values['plnphs_date_echeance'] < $values['plnphs_date_debut']) {
							$this->setMessage('invalid', 'La date d\'échéance est antérieure à celle de début');
							throw new sfValidatorErrorSchema($this, array(
								'plnphs_date_echeance' => new sfValidatorError($this, 'invalid')
							));
						}
					}
					break;
			}
		}
		return $values;
	}
}
